#!/usr/bin/perl -w

package XmlDomParser;

use strict;
use XML::Parser;
use XmlElementObj;

use Exporter;
our @ISA=qw/Exporter/;
our @EXPORT=qw//;
our @EXPORT_OK=qw/ParseData ParseFile/;

sub Init;
sub Final;
sub Start;
sub End;
sub Char;
sub Comment;
sub CdataStart;
sub CdataEnd;

my $root=undef;
my $length=0;
my $currentElement=$root;

sub ParseData
{
	$root=undef;
	$length=0;
	my $data=shift;
	my $parser=new XML::Parser(Handlers=>{
			Init=>\&Init,
			Start=>\&Start,
			End=>\&End,
			Char=>\&Char,
			Comment=>\&Comment,
			CdataStart=>\&CdataStart,
			CdataEnd=>\&CdataEnd,
			Final=>\&Final

		});
	$parser->parse($data);
	return $root;
}

sub ParseFile
{
	$root=undef;
	$length=0;
	my $file=shift;
	my $parser=new XML::Parser(Handlers=>{
			Init=>\&Init,
			Start=>\&Start,
			End=>\&End,
			Char=>\&Char,
			Comment=>\&Comment,
			CdataStart=>\&CdataStart,
			CdataEnd=>\&CdataEnd,
			Final=>\&Final

		});
	$parser->parsefile($file);
	return $root;
}

sub Init
{
	$root=XmlElementObj->new();
}

sub Final
{
}

sub Start
{
	my $expat=shift;
	my $tag=shift;
	my %hash;
	my $key;
	my $value;

	while(my $key=shift)
	{
		$value=shift;
		$hash{$key}=$value;
	}

	my $element=&GetCurrentElement();

	if ($element == $root)
	{
		$root->TagName($tag);
		$root->Attribute(%hash);
	}
	else
	{
		my $child=XmlElementObj->new($tag);
		$child->Attribute(%hash);
		$element->AddChild($child);
	}
	$length++;
}

sub End
{
	$length--;
}

sub Char
{
}

sub Comment
{
}

sub CdataStart
{
}

sub CdataEnd
{
}

sub GetCurrentElement
{
	if ($length == 0)
	{
		return $root;
	}
	else
	{
		return $root->Child($length);
	}
}

1;

